package com.project.smarthome.login.presenter;

import android.os.CountDownTimer;

import com.project.smarthome.R;
import com.project.smarthome.base.BasePresenter;
import com.project.smarthome.common.util.StringUtils;
import com.project.smarthome.common.util.UIUtils;
import com.project.smarthome.login.RegistContract;
import com.sds.smarthome.business.domain.UserService;
import com.sds.smarthome.business.domain.entity.GetVerCodeResult;
import com.sds.smarthome.business.domain.entity.RegistResult;
import com.sds.smarthome.business.domain.service.DomainFactory;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Created by lunanting on 2016/10/21.
 */

public class RegistPresenter extends BasePresenter implements RegistContract.Presenter {

    private UserService mUserService;
    private RegistContract.View mView;
    private CountDownTimer mCountDownTimer;

    public RegistPresenter(RegistContract.View view) {
        mView = view;
        mUserService = DomainFactory.getUserService();
    }

    @Override
    public void init() {
        super.init();
    }

    @Override
    public void getVerCode(final String phoneNum) {
        if (phoneNum.isEmpty()) {
            mView.showToast(UIUtils.getString(R.string.phoneNumIsNull));
            return;
        }

        if (!StringUtils.isTel(phoneNum)) {
            mView.showToast(UIUtils.getString(R.string.inputTheRightPhoneNum));
            return;
        }

        Observable<GetVerCodeResult> observable = Observable.create(new ObservableOnSubscribe<GetVerCodeResult>() {
            @Override
            public void subscribe(ObservableEmitter<GetVerCodeResult> e) throws Exception {
                GetVerCodeResult getVerCodeResult = mUserService.getVerCode(phoneNum, 1);

                if (getVerCodeResult != null) {
                    e.onNext(getVerCodeResult);
                } else {
                    e.onError(new Throwable("get verification code error"));
                }
            }

        });
        Disposable subscribe = observable.subscribeOn(getJobExecutor())
                .observeOn(getUiExecutor()).subscribe(new Consumer<GetVerCodeResult>() {

                    @Override
                    public void accept(GetVerCodeResult getVerCodeResult) throws Exception {
                        if (getVerCodeResult.isSuccess()) {
                            mView.showToast(UIUtils.getString(R.string.getVerificationCodeSuccess));

                            mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    mView.showCoutDownTime(millisUntilFinished / 1000);
                                }

                                @Override
                                public void onFinish() {
                                    mView.showFinish();
                                }
                            }.start();
                        } else {
                            mView.showToast(getCloudErrorDesc(getVerCodeResult.getError().getErrorCode()));
                        }
                    }
                });
        addSubscription(subscribe);
    }

    @Override
    public void toRegist(final String phoneNum, final String password, final String verCode) {
        if (phoneNum.isEmpty()) {
            mView.showToast(UIUtils.getString(R.string.phoneNumIsNull));
            return;
        }

        if (!StringUtils.isTel(phoneNum)) {
            mView.showToast(UIUtils.getString(R.string.inputTheRightPhoneNum));
            return;
        }

        if (verCode.isEmpty()) {
            mView.showToast(UIUtils.getString(R.string.verificationCodeIsNull));
            return;
        }

        if (password.isEmpty()) {
            mView.showToast(UIUtils.getString(R.string.login_inputPasswordHint));
            return;
        }

        if (password.length() < 6 || password.length() >= 16) {
            mView.showToast(UIUtils.getString(R.string.phoneNum_length));
            return;
        }

        Observable<RegistResult> observable = Observable.create(new ObservableOnSubscribe<RegistResult>() {
            @Override
            public void subscribe(ObservableEmitter<RegistResult> e) throws Exception {
                RegistResult registResult = mUserService.toRegist(phoneNum, password, verCode);
                if (registResult != null) {
                    e.onNext(registResult);
                } else {
                    e.onError(new Throwable("get verification code error"));
                }
            }

        });
        Disposable subscription = observable.subscribeOn(getJobExecutor())
                .observeOn(getUiExecutor()).subscribe(new Consumer<RegistResult>() {
                    @Override
                    public void accept(RegistResult registResult) throws Exception {
                        if (registResult.isSuccess()) {
                            mView.loginSuccessToMain();
                        } else {
                            mView.showToast(getCloudErrorDesc(registResult.getError().getErrorCode()));
                        }
                    }

                });
        addSubscription(subscription);
    }

    @Override
    public void destroy() {
        super.destroy();
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }
}
